package sqlUtil;

import java.util.List;

/**
 * Created by yangfan on 2016/10/20.
 */
public class MakeSql {
    private final static String SELECT = "SELECT ";
    private final static String FROM = " FROM ";
    private final static String WHERE = " WHERE ";
    private final static String SPACE = " ";
    private final static String COMMA = ",";
    private final static String AND = " AND ";
    private final static String ORDER_BY = " ORDER BY ";

    private MakeSql() {
    }

    /**
     * 生成select Sql语句
     *
     * @param selectParameters
     * @param selectTableNames
     * @param selectConditions
     * @return select Sql
     */
    public static StringBuffer getSelectSql(List<String> selectParameters, List<String> selectTableNames, List<String> selectConditions) {
        StringBuffer sql = new StringBuffer();
        sql.append(SELECT);
        //拼接select参数parameter
        StringBuffer parameters = getSplitJoint(selectParameters, COMMA);
        sql.append(parameters);

        sql.append(FROM);
        StringBuffer tableNames = getSplitJoint(selectTableNames, COMMA);
        sql.append(tableNames);

        sql.append(WHERE);
        StringBuffer conditions = getSplitJoint(selectConditions, AND);
        sql.append(conditions);

        return sql;
    }

    /**
     * 生成带有排序的select Sql语句
     *
     * @param selectParameters
     * @param selectTableNames
     * @param selectConditions
     * @return select Sql with order
     */
    public static StringBuffer getOrderSelect(List<String> selectParameters, List<String> selectTableNames, List<String> selectConditions, List<String> orderCondition) {
        StringBuffer sql = new StringBuffer();
        sql = getSelectSql(selectParameters, selectTableNames, selectConditions);
        sql.append(ORDER_BY);
        sql.append(getSplitJoint(orderCondition, COMMA));
        return sql;
    }

    /**
     * 拼接字符串
     *
     * @param splitJointParameter
     * @param separator
     * @return split joint with separator
     */
    private static StringBuffer getSplitJoint(List<String> splitJointParameter, String separator) {
        StringBuffer parameters = new StringBuffer();
        for (int i = 0; i < splitJointParameter.size(); i++) {
            if (i == 0) {
                parameters.append(splitJointParameter.get(i));
            } else {
                parameters.append(separator);
                parameters.append(splitJointParameter.get(i));
            }
        }
        return parameters;
    }
}
